/*
 * Copyright 2009 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.gtugs.web;

import org.gtugs.domain.Chapter;
import org.gtugs.domain.Event;
import org.gtugs.service.ChapterManager;
import org.gtugs.service.EventManager;
import org.gtugs.service.security.AppEngineUserService;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author jasonacooper@google.com (Jason Cooper)
 */
public class ReportController implements Controller {

  private ChapterManager chapterManager;
  private EventManager eventManager;

  public ModelAndView handleRequest(HttpServletRequest request,
      HttpServletResponse response) throws ServletException, IOException {
    Map<String, Object> model = new HashMap<String, Object>();

    AppEngineUserService userService = new AppEngineUserService();
    model.put("userService", userService);

    List<Chapter> allChapters = chapterManager.getChapters();
    List<Event> allEvents = eventManager.getEvents();

    final HashMap<Long, Integer> eventsGroupedByChapterId =
      new HashMap<Long, Integer>();
    final HashMap<Long, Integer> allEventsGroupedByChapterId =
      new HashMap<Long, Integer>();

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.MONTH, -3);

    List<Event> events = eventManager.getEvents(cal.getTime(), new Date());
    for (Event event : events) {
      long chapterId = event.getChapterId();

      if (eventsGroupedByChapterId.containsKey(chapterId)) {
        int eventCount = eventsGroupedByChapterId.get(chapterId);
        eventsGroupedByChapterId.put(chapterId, eventCount + 1);
      } else {
        eventsGroupedByChapterId.put(chapterId, 1);
      }
    }
    for (Event event : allEvents) {
      long chapterId = event.getChapterId();

      if (allEventsGroupedByChapterId.containsKey(chapterId)) {
        int eventCount = allEventsGroupedByChapterId.get(chapterId);
        allEventsGroupedByChapterId.put(chapterId, eventCount + 1);
      } else {
        allEventsGroupedByChapterId.put(chapterId, 1);
      }
    }

    HashMap<Long, Chapter> chapterResults = new HashMap<Long, Chapter>();

    for (Chapter chapter: allChapters) {
      if (eventsGroupedByChapterId.containsKey(chapter.getId())) {
        chapter.setNumEvents(eventsGroupedByChapterId.get(chapter.getId()));
      } else {
        chapter.setNumEvents(0);
      }
      if (allEventsGroupedByChapterId.containsKey(chapter.getId())) {
        chapter.setNumEventsTotal(allEventsGroupedByChapterId.get(chapter.getId()));
      } else {
        chapter.setNumEventsTotal(0);
      }
      chapterResults.put(chapter.getId(), chapter);
    }

    model.put("chapterEventsCounts", sortByValues(chapterResults));

    return new ModelAndView("report", "model", model);
  }

  // From Anthony at http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java
  private static <K, V extends Comparable<V>> Map<K, V> sortByValues(
      final Map<K, V> map) {
    Comparator<K> valueComparator = new Comparator<K>() {
      public int compare(K k1, K k2) {
        int result = map.get(k2).compareTo(map.get(k1));
        if (result == 0) {
          return 1;
        } else {
          return result;
        }
      }
    };

    Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);
    sortedByValues.putAll(map);

    return sortedByValues;
  }

  public void setChapterManager(ChapterManager chapterManager) {
    this.chapterManager = chapterManager;
  }

  public void setEventManager(EventManager eventManager) {
    this.eventManager = eventManager;
  }
}
